type bannerType = "default"
type videoType = "default" 
type interstitialType = "default"
const data = {
    "wechatgame": {
        "banner": {
            "default": "",
        },
        "video": {
            "default": "",
        },
        "interstitial": {
            "default": "",
        }
    },
    "bytedance": {
        "banner": {
            "default": "",
        },
        "video": {
            "default": ""
        }
    },
    "baidugame": {
        appSid: "",
        "video": {
            "default": "",
        },
        "banner": {
            "addMoney": "",
        }
    }
}
/**
 * 广告管理
 */
class AdvertisingManagement {
    private videoAd: Map<String, any> | any = null;
    private bannerAd: Map<String, any> | any = null;
    private interstitialAd: Map<String, any> = null
    private gridAd: any = null
    /**
     * 创建激励广告实例
     */
    createRewardedVideoAd() {
        //@ts-ignore
        if (typeof uc != 'undefined') {
            //uc没有appid,平台自动分配
            // @ts-ignore
            this.videoAd = uc.createRewardVideoAd();
            this.videoAd.onLoad(this.onLoadVideo);
            this.videoAd.onError(this.onError)
        } else if (cc.sys.platform === cc.sys.BYTEDANCE_GAME) {
            //只能是单例模式
            //@ts-ignore
            this.videoAd = tt.createRewardedVideoAd({ adUnitId: data.bytedance.video.default });
            this.videoAd.onLoad(this.onLoadVideo);
            this.videoAd.onError(this.onError)
        } else if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            //微信采用多例模式
            this.videoAd = new Map();
            for (let key in data.wechatgame.video) {
                //@ts-ignore
                let videoAd = wx.createRewardedVideoAd({ adUnitId: data.wechatgame.video[key], multiton: false });
                videoAd.onLoad(this.onLoadVideo);
                videoAd.onError(this.onError)
                this.videoAd.set(key, videoAd)
            }
        } else if (cc.sys.platform === cc.sys.BAIDU_GAME) {//百度
            //只能是单例模式
            //@ts-ignore
            this.videoAd = swan.createRewardedVideoAd({ adUnitId: data.baidugame.video.default, appSid: data.baidugame.appSid });
            this.videoAd.onLoad(this.onLoadVideo);
            this.videoAd.onError(this.onError)
        }
    }
    /**
     * 播放激励广告
     * @param key 广告位名称
     * @param successCallback 激励广告视频播放完后，回调函数
     * @param failCallBack 没看完激励广告关闭视频后,回调函数
     */
    showVideo(key: advertisingType, successCallback: Function, failCallBack?: Function) {
        let videoAd = null
        if (this.videoAd instanceof Map) {//map对象====>WX
            videoAd = this.videoAd.get(key);
            if (!videoAd) {
                console.error("请传入一个有效key")
            }
        } else if (this.videoAd instanceof Object) {//一个对象====>UC and TT
            videoAd = this.videoAd;
        }

        if (videoAd) {
            let closeCallFun = res => {
                if (res && res.isEnded || res === undefined) {
                    // 正常播放结束，可以下发游戏奖励
                    successCallback();//执行回调函数函数
                }
                else {
                    // 播放中途退出，不下发游戏奖励
                    if (failCallBack) {
                        failCallBack();
                    }
                }
                videoAd.offClose(closeCallFun)//取消监听
            }
            videoAd.onClose(closeCallFun);
            videoAd.show().catch(() => {
                // 失败重试
                videoAd.load().then(() => videoAd.show()).catch(err => { console.warn('激励视频 广告显示失败') })
            })
        } else {
            if (failCallBack) {
                failCallBack();
            }
        }
    }

    /**
     * 创建banner广告实例
     */
    createBannerAd() {
        //@ts-ignore
        if (typeof uc != "undefined") {
            //uc没有appid,平台自动分配
            // @ts-ignore
            let res = uc.getSystemInfoSync();
            if (typeof res === 'string') {
                try {
                    res = JSON.parse(res);
                } catch (e) { }
            }

            let deviceWidth = res.screenWidth > res.screenHeight ? res.screenHeight : res.screenWidth;
            let width = deviceWidth / 2;
            if (cc.view.getFrameSize().width > cc.view.getFrameSize().height) {//横屏幕
                width = 300;
            }
            let height = (width * 194) / 345;
            //@ts-ignore
            this.bannerAd = uc.createBannerAd({
                style: {
                    width: width,
                    height: height,
                    gravity: 7//banner广告的位置（默认为0）0：左上,1：顶部居中,2：右上,3：左边垂直居中,4：居中,5：右边垂直居中,6：左下,7：底部居中,8：右下
                }
            });
            this.bannerAd.onLoad(this.onLoadBanner);
            this.bannerAd.onError(this.onError)
        } else if (cc.sys.platform === cc.sys.BYTEDANCE_GAME) {
            this.bannerAd = new Map();
            for (let key in data.bytedance.banner) {
                //@ts-ignore
                let { windowWidth, windowHeight, } = tt.getSystemInfoSync()
                let style = {
                    top: 0, left: 0, width: windowWidth
                }
                if (cc.view.getFrameSize().width > cc.view.getFrameSize().height) {//横屏幕
                    style.width = 300
                }
                //@ts-ignore
                let bannerAd = tt.createBannerAd({
                    adUnitId: data.bytedance.banner[key],
                    adIntervals: 30, // 自动刷新频率不能小于30秒
                    style: {
                        left: 0,
                        top: 0,
                        width: 300
                    }
                });
                bannerAd.onResize(res => {
                    //@ts-ignore
                    bannerAd.style.top = windowHeight - res.height
                    bannerAd.style.left = (windowWidth - res.width) / 2
                })
                bannerAd.onLoad(this.onLoadBanner);
                bannerAd.onError(this.onError)
                this.bannerAd.set(key, bannerAd)
            }
        } else if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            this.bannerAd = new Map();
            //@ts-ignore
            let { screenHeight, screenWidth, } = wx.getSystemInfoSync()
            let style = {
                left: 0,
                top: 0,
                width: screenWidth,
            }
            if (cc.view.getFrameSize().width > cc.view.getFrameSize().height) {//横屏幕
                style.width = 300;
            }
            for (let key in data.wechatgame.banner) {
                //@ts-ignore
                let bannerAd = wx.createBannerAd({
                    adUnitId: data.wechatgame.banner[key],
                    adIntervals: 30, // 自动刷新频率不能小于30秒
                    style: style
                });
                bannerAd.onResize(res => {
                    bannerAd.style.top = screenHeight - res.height
                    bannerAd.style.left = (screenWidth - res.width) / 2
                })
                bannerAd.onLoad(this.onLoadBanner);
                bannerAd.onError(this.onError)
                this.bannerAd.set(key, bannerAd)
            }
        } else if (cc.sys.platform === cc.sys.BAIDU_GAME) {
            this.bannerAd = new Map();
            //@ts-ignore
            let { screenHeight, screenWidth } = swan.getSystemInfoSync()
            let style = {
                top: 0, left: 0, width: screenWidth
            }
            if (cc.view.getFrameSize().width > cc.view.getFrameSize().height) {//横屏幕
                style.width = 300;
            }
            for (let key in data.baidugame.banner) {
                //@ts-ignore
                let bannerAd = swan.createBannerAd({
                    appSid: data.baidugame.appSid,
                    adUnitId: data.baidugame.banner[key],
                    adIntervals: 30, // 自动刷新频率不能小于30秒
                    style: style
                });
                bannerAd.onResize(res => {
                    bannerAd.style.top = screenHeight - res.height
                    bannerAd.style.left = (screenWidth - res.width) / 2
                })
                bannerAd.onLoad(this.onLoadBanner);
                bannerAd.onError(this.onError)
                this.bannerAd.set(key, bannerAd)
            }
        }
    }
    /**
     * 显示banner广告
     * @param key 广告位名称
     */
    showBanner(key?: bannerType) {
        if (this.bannerAd instanceof Map) {//微信,字节
            if (this.bannerAd.get(key)) {
                //关闭已存在的banner广告
                this.hideBanner(key);
                // if (cc.sys.platform === cc.sys.BAIDU_GAME) {//手动触发改变banner位置
                //     let bannerAd = this.bannerAd.get(key)
                //     //@ts-ignore
                //     let { screenHeight, screenWidth } = swan.getSystemInfoSync()
                //     let res = bannerAd.style;
                //     bannerAd.style.top = screenHeight - res.height
                //     bannerAd.style.width = screenWidth
                //     bannerAd.style.left = (screenWidth - res.width) / 2
                // }
                this.bannerAd.get(key).show()
            } else {
                console.error("请传入一个有效key")
            }
        } else if (this.bannerAd instanceof Object) {//其他平台
            this.hideBanner();
            this.bannerAd.show()
        }
    }
    /**
     * 关闭当前banner广告
     * @param key 广告位名称
     */
    hideBanner(key?: bannerType) {
        if (this.bannerAd instanceof Map) {//map对象
            if (this.bannerAd.get(key)) {
                this.bannerAd.get(key).hide()
            } else {
                console.error("请传入一个有效key")
            }
        } else if (this.bannerAd instanceof Object) {//一个对象
            this.bannerAd.hide()
        }
    }
    /**
     * 创建插屏广告
     */
    createInterstitialAd() {
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            this.interstitialAd = new Map();
            for (let key in data.wechatgame.interstitial) {
                //@ts-ignore
                let interstitialAd = wx.createInterstitialAd({ adUnitId: data.wechatgame.interstitial[key] })
                interstitialAd.onLoad(this.onLoadInterstitialAd)
                interstitialAd.onError(this.onError)
                interstitialAd.onClose(this.onCloseInterstitialAd)
                this.interstitialAd.set(key, interstitialAd)
            }
        }
    }
    /**
     * 显示插屏广告
     * @param key 广告位
     */
    showInterstitialAd(key: interstitialType) {
        if (this.interstitialAd) {

            let interstitialAd = this.interstitialAd.get(key);
            // 在适合的场景显示插屏广告
            if (interstitialAd) {
                interstitialAd.show().catch((err) => {
                    console.error(err)
                })
            } else {
                console.error("请输入一个有效key")
            }
        } else {
            console.error("未创建插屏广告")
        }
    }
    /**
     * 创建格子广告
     */
    createGridAd() {
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            // 创建格子广告实例，提前初始化
            //@ts-ignore
            this.gridAd = wx.createGridAd({
                adUnitId: data.wechatgame.grid.default,
                adTheme: 'white',
                gridCount: 5,
                style: {
                    left: 0,
                    top: 0,
                    width: 330,
                    opacity: 0.8
                }
            })
            this.gridAd.onError(this.onError)
        }
    }
    /**
     * 显示格子广告
     * @param key 
     */
    showGridAd(key: gridType) {
        if (this.gridAd) {
            if (cc.sys.platform === cc.sys.WECHAT_GAME) {
                this.gridAd.show()
            }
        }
    }
    /**
     *隐藏格子广告
     * @param key 
     */
    hideGridAd(key: gridType) {
        if (this.gridAd) {
            if (cc.sys.platform === cc.sys.WECHAT_GAME) {
                this.gridAd.hide()
            }
        }
    }
    /**
     * 激励广告加载回调函数
     */
    private onLoadVideo() {
        console.info("激励广告加载成功")
    }
    /**
     * banner 广告加载回调函数
     */
    private onLoadBanner() {
        console.info("banner 广告加载成功")
    }
    /**
     * 插屏 广告加载回调函数
     */
    private onLoadInterstitialAd() {
        console.info("interstitialAd 广告加载成功")
    }
    /**
     * 插屏 广告关闭回调函数
     */
    private onCloseInterstitialAd(res) {
        console.log('插屏 广告关闭')
    }
    /**
     * 错误回调函数
     */
    private onError() {
        // Util.showToast("网络请求失败")
    }
}
export default new AdvertisingManagement();